package net.elib.controller;

import net.elib.entity.Book;
import net.elib.service.BookService;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Created by IntelliJ IDEA.
 * User: ked
 * Date: 21.08.12
 * Time: 20:55
 * To change this template use File | Settings | File Templates.
 */
public class BookController extends MultiActionController{
    private BookService bookService;

    public void setBookService(BookService bookService) {
        this.bookService = bookService;
    }

    public ModelAndView upload(HttpServletRequest request,
                               HttpServletResponse response) throws Exception {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("file");

        Book book = new Book();
        book.setFilename(multipartFile.getOriginalFilename());
        book.setType(multipartFile.getContentType());
        book.setFile(multipartFile.getBytes());
        book.setBookName(ServletRequestUtils.getStringParameter(request, "bookName"));
        book.setBookAuthor(ServletRequestUtils.getStringParameter(request, "bookAuthor"));
        book.setBookPublishing(ServletRequestUtils.getStringParameter(request, "bookPublishing"));
        book.setBookDescription(ServletRequestUtils.getStringParameter(request, "bookDescription"));

        this.bookService.save(book);

        return new ModelAndView("redirect:files.htm");
    }

    public ModelAndView download(HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        int id = ServletRequestUtils.getRequiredIntParameter(request, "id");

        Book book = this.bookService.find(id);

        response.setContentType(book.getFilename());
        response.setContentLength(book.getFile().length);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + book.getFilename() + "\"");

        FileCopyUtils.copy(book.getFile(), response.getOutputStream());

        return null;

    }

    public ModelAndView delete(HttpServletRequest request,
                               HttpServletResponse response) throws Exception {
        int id = ServletRequestUtils.getRequiredIntParameter(request, "id");

        this.bookService.delete(id);

        return new ModelAndView("redirect:files.htm");
    }
}
